package db

import (
	myDb "filestore-server/db/mysql"
	"fmt"
)

// User 用户表 model
type User struct {
	Username     string
	Email        string
	Phone        string
	SignupAt     string
	LastActiveAt string
	Status       int
}

// UserSignUp 通过用户名和密码完成 user 表的注册
func UserSignUp(username string, passwd string) bool {
	stmtIns, err := myDb.DBConn().Prepare("INSERT IGNORE INTO tbl_user (user_name, user_pwd) VALUES (?, ?)")
	if err != nil {
		fmt.Printf("Failed to insert user, err: %s", err.Error())
		return false
	}
	defer stmtIns.Close()

	result, err := stmtIns.Exec(username, passwd)
	if err != nil {
		fmt.Printf("Failed to insert user, err: %s", err.Error())
		return false
	}

	// 多一步判断是否重复注册，执行力 sql 并没有插入数据
	if rowAffected, err := result.RowsAffected(); err == nil && rowAffected > 0 {
		return true
	}

	return false
}

// UserSignIn 判断密码是否一致
func UserSignIn(username, encpwd string) bool {
	stmtOut, err := myDb.DBConn().Prepare("SELECT * FROM tbl_user WHERE user_name = ? limit 1")
	if err != nil {
		fmt.Printf("Failed to query user, err: %s", err.Error())
		return false
	}
	defer stmtOut.Close()

	row, err := stmtOut.Query(username)
	if err != nil {
		fmt.Printf("Failed to query user by name: %s, err: %s", username, err.Error())
		return false
	} else if row == nil {
		fmt.Printf("username not foud:%s", username)
		return false
	}

	// 如果查询到了用户数据
	parseRows := myDb.PareRows(row)
	if len(parseRows) > 0 && string(parseRows[0]["user_pwd"].([]byte)) == encpwd {
		return true
	}

	return false
}

// UpdateToken 刷新用户登录的 token
func UpdateToken(username, token string) bool {
	stmtOut, err := myDb.DBConn().Prepare("REPLACE INTO tbl_user_token (user_name, user_token) VALUES (?, ?)")
	if err != nil {
		fmt.Printf("Filed to update token, err: %s", err.Error())
		return false
	}
	defer stmtOut.Close()

	_, err = stmtOut.Exec(username, token)
	if err != nil {
		fmt.Printf("Filed to update token, err: %s", err.Error())
		return false
	}

	return true
}

// GetUserInfo 用户信息查询
func GetUserInfo(username string) (User, error) {
	user := User{}

	stmtOut, err := myDb.DBConn().Prepare("SELECT user_name, signup_at FROM tbl_user WHERE user_name = ? limit 1")
	if err != nil {
		fmt.Printf("Failed to query user, err: %s", err.Error())
		return user, err
	}
	defer stmtOut.Close()

	// 执行查询操作
	err = stmtOut.QueryRow(username).Scan(&user.Username, &user.SignupAt)
	if err != nil {
		fmt.Printf("Failed to query user, err: %s", err.Error())
		return user, err
	}

	return user, nil
}

// UserExist : 查询用户是否存在
func UserExist(username string) (bool, error) {

	stmt, err := myDb.DBConn().Prepare(
		"select 1 from tbl_user where user_name=? limit 1")
	if err != nil {
		fmt.Println(err.Error())
		return false, err
	}
	defer stmt.Close()

	rows, err := stmt.Query(username)
	if err != nil {
		return false, err
	}
	return rows.Next(), nil
}
